package com.example.drive.fragment

import com.example.drive.base.BaseFragment
import android.widget.PopupWindow
import android.view.LayoutInflater
import android.text.TextUtils
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import android.graphics.drawable.ColorDrawable
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.example.drive.DrivingAnswer
import com.example.drive.JZTKViewModel
import com.example.drive.R
import com.example.drive.bean.ResultBean
import com.example.drive.databinding.FragmentMainBinding
import com.example.drive.db.JZTKDataBase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.*

/**
 * 主页面Fragment
 */
class MainFragment : BaseFragment<FragmentMainBinding>() {
    companion object {
        private const val TAG = "DrivingMainFragment"
    }

    private lateinit var jztkViewModel: JZTKViewModel

    private val fragments = mutableListOf<QuestionFragment>()
    private var answerDetailFragment: AnswerDetailFragment? = null
    private var popupWindow: PopupWindow? = null

    /**
     * 保存答题情况
     */
    private val linkedHashMap = LinkedHashMap<Int, DrivingAnswer>()

    override fun initViewBinding(inflater: LayoutInflater): FragmentMainBinding {
        return FragmentMainBinding.inflate(inflater)
    }

    override fun initData() {
        jztkViewModel = ViewModelProvider(this)[JZTKViewModel::class.java]
        jztkViewModel.queryJZTK()
        jztkViewModel.resultBeanList.observe(this) {
            it?.run {
                handleChange(this)
            }
        }
    }

    private fun handleChange(list: List<ResultBean>) {
        // 恢复上次的答题情况,这里逻辑略显复杂,理清思路
        lifecycleScope.launch(Dispatchers.IO) {
            val drivingAnswerBeans = JZTKDataBase.drivingAnswerBeanDao.queryAll()
            withContext(Dispatchers.Main) {
                val myAnswers: MutableList<Int?> = ArrayList()
                if (drivingAnswerBeans != null && drivingAnswerBeans.isNotEmpty()) {
                    for (answerBean in drivingAnswerBeans) {
                        myAnswers.add(answerBean.id)
                    }
                }
                var myAnswer: String?
                for (resultBean in list) {
                    if (myAnswers.contains(resultBean.id)) {
                        val index = myAnswers.indexOf(resultBean.id)
                        myAnswer = drivingAnswerBeans?.get(index)?.myAnswer
                        val drivingAnswer = if (TextUtils.equals(myAnswer, resultBean.answer)) {
                            DrivingAnswer.RIGHT
                        } else {
                            DrivingAnswer.WRONG
                        }
                        putAnswer(resultBean.id!!, drivingAnswer)
                    } else {
                        myAnswer = ""
                        putAnswer(resultBean.id!!, DrivingAnswer.UNFINISHED)
                    }
                    fragments.add(QuestionFragment.newInstance(resultBean, myAnswer))
                }

                val adapter = object : FragmentStateAdapter(this@MainFragment) {
                    override fun getItemCount(): Int {
                        return fragments.size
                    }

                    override fun createFragment(position: Int): Fragment {
                        return fragments[position]
                    }
                }
                binding?.viewPager2?.orientation = ViewPager2.ORIENTATION_HORIZONTAL
                binding?.viewPager2?.adapter = adapter
                binding?.viewPager2?.offscreenPageLimit = 1
                binding?.viewPager2?.registerOnPageChangeCallback(object : OnPageChangeCallback() {
                    override fun onPageSelected(position: Int) {
                        super.onPageSelected(position)
                        // id从1开始的,不需要+1
                        val current = list[position].id
                        val text = String.format(Locale.ENGLISH, "%d/%d", current, fragments.size)
                        binding?.tvNumber?.text = text
                    }
                })

                // 设置滑动方向
                binding?.ivSettings?.setOnClickListener {
                    if (popupWindow == null) {
                        popupWindow = PopupWindow(context)
                        val contentView = View.inflate(context, R.layout.driving_settings, null)
                        contentView.findViewById<View>(R.id.tv_horizontal).setOnClickListener {
                            binding?.viewPager2?.orientation = ViewPager2.ORIENTATION_HORIZONTAL
                            popupWindow?.dismiss()
                        }
                        contentView.findViewById<View>(R.id.tv_vertical).setOnClickListener {
                            binding?.viewPager2?.orientation = ViewPager2.ORIENTATION_VERTICAL
                            popupWindow?.dismiss()
                        }
                        popupWindow?.contentView = contentView
                        // 去掉黑边框
                        popupWindow?.setBackgroundDrawable(ColorDrawable(0))
                        popupWindow?.isFocusable = true
                        popupWindow?.isOutsideTouchable = true
                    }
                    if (popupWindow?.isShowing == true) {
                        popupWindow?.dismiss()
                    } else {
                        popupWindow?.showAsDropDown(it)
                    }
                }

                // 查看题库
                answerDetailFragment = AnswerDetailFragment {
                    answerDetailFragment?.refreshData(linkedHashMap)
                }
                binding?.ivAnswer?.setOnClickListener {
                    answerDetailFragment?.show(childFragmentManager, TAG)
                }
            }
        }
    }

    fun putAnswer(which: Int, drivingAnswer: DrivingAnswer) {
        linkedHashMap[which] = drivingAnswer
    }

    fun onPageSelected(position: Int) {
        binding?.viewPager2?.currentItem = position
    }
}